<template>
    <div class="content">
        <div class="page-head">
            <span class="head-text">停机报工</span>
            <span class="head-text">当前用户：{{ userInfo.username }}</span>
        </div>
        <div class="page-main">
            <div class="main-head">
                <el-radio-group v-model="formData.workshop">
                    <el-radio :label="0">装配线</el-radio>
                    <el-radio :label="1">机加工</el-radio>
                    <el-radio :label="2">走心机</el-radio>
                </el-radio-group>
            </div>
            <div class="main-center">
                <el-form :model="formData" ref="formData" :rules="formDataRules" label-width="100px" label-position="left" size="mini" :hide-required-asterisk="false" class="demo-ruleForm">
                    <el-form-item label="日期" prop="reportDate" size="small">
                        <el-date-picker v-model="formData.reportDate" :editable="false" value-format="yyyy-MM-dd" type="date" size="mini" style="width:200px;" placeholder="选择日期时间" class="el-date-picker"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="班次" prop="classList">
                        <el-checkbox-group v-model="formData.classList">
                            <el-checkbox v-for="v,i in classesList" :label="v.shiftType" :key="i"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="设备/线体" prop="equipmentOrLineList">
                        <el-checkbox v-model="isAllSelected" label="选择全部"></el-checkbox>
                        <div class="el-form-item-content">
                            <el-checkbox-group v-if="formData.workshop === 1 || formData.workshop === 2" v-model="formData.equipmentOrLineList">
                                <el-checkbox v-for="v,i in deviceList" :label="v.deviceCode" :key="i"></el-checkbox>
                            </el-checkbox-group>
                            <el-checkbox-group v-else v-model="formData.equipmentOrLineList">
                                <el-checkbox v-for="v,i in lineList" :label="v" :key="i"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                    <el-form-item label="停机原因" prop="downtReason">
                        <el-radio-group v-model="formData.downtReason">
                            <el-radio label="缺刀具" style="margin:5px 8px;">缺刀具</el-radio>
                            <el-radio label="缺料" style="margin:5px 8px;">缺料</el-radio>
                            <el-radio label="刀具异常" style="margin:5px 8px;">刀具异常</el-radio>
                            <el-radio label="计划停机" style="margin:5px 8px;">计划停机</el-radio>
                            <el-radio label="设备故障" style="margin:5px 8px;">设备故障</el-radio>
                            <el-radio label="产品换型" style="margin:5px 8px;">产品换型</el-radio>
                            <el-radio label="来料质量异常" style="margin:5px 8px;">来料质量异常</el-radio>
                            <el-radio label="其它" style="margin:5px 8px;">其它</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-footer">
                <el-button type="primary" size="small" class="footer-btn" @click="cancelButton">取消</el-button>
                <el-button type="success" size="small" class="footer-btn" @click="confirmButton">确定</el-button>
            </div>
        </div>
    </div>
</template>
  
<script>
import { reqUserInfo, reqProductOrderList, reqMaterialsInfo, reqClassesList, reqLineList, getDeviceAPI } from "@/api/workOrder.js";
import { reqMaterialListByGrid, reqEntryWarehouse } from "@/api/warehouseEntry.js";
import { reqMachieHaltReport } from "@/api/machineHaltReport.js";
import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
export default {
    name:"machineHaltReport",  //停机报工
    data() {
        const validate1 = (rule, value, callback) => {
            if (value.length === 0) {
                callback(new Error('请选择至少一个班次'));
            } else {
                callback();
            }
        };
        const validate2 = (rule, value, callback) => {
            if (value.length === 0) {
                callback(new Error('请选择设备或线体'));
            } else {
                callback();
            }
        };
        return {
            userInfo:{
                username:"",
                userId:"",
                userPhone:"",
                user:"",
                classTeamList:[]
            },
            formData:{
                workshop:0,  //车间 1机加工、2走心机、3装配车间
                reportDate:this.formatDate(null,1),
                classList:[],
                equipmentOrLineList:[],
                downtReason:""
            },
            formDataRules:{
                reportDate:[{required:true, message:"请选择报工日期", trigger: 'change'}],
                classList:[{required:true, validator:validate1, trigger: 'change'}],
                equipmentOrLineList:[{required:true, validator:validate2, trigger: 'change'}],
                downtReason:[{required:true, message:"请选择停机原因", trigger: 'change'}]
            },
            classesList:[],
            deviceList:[],
            lineList:[],
            isAllSelected:false
        };
    },
    watch:{
        "formData.workshop":{
            handler(newValue,oldValue){
                this.lineList = [];
                this.deviceList = [];
                this.formData.equipmentOrLineList = [];
                if(this.$refs.formData){
                    this.$refs.formData.resetFields();
                }
                newValue > 0 ? this.getDeviceList() : this.getLineList();
                this.isAllSelected = false;
            },
            immediate:true
        },
        isAllSelected:{
            handler(newValue,oldValue){
                const workshop = this.formData.workshop;
                const list = new Array();
                if(newValue){
                    let tmp = workshop > 0 ? this.deviceList : this.lineList;
                    if(tmp.length === 0){
                        this.isAllSelected = false;
                    }
                    for(let i = 0; i < tmp.length; i ++){
                        let deviceCodeOrLineName = workshop > 0 ? tmp[i].deviceCode : tmp[i];
                        list.push(deviceCodeOrLineName);
                    }
                    this.formData.equipmentOrLineList = list;
                } else {
                    this.formData.equipmentOrLineList = [];
                }
            }
        }
    },
    mounted(){
        //精致环境下进行自动转屏
        //autoOrientation();
        //精致平台获取用户信息可能不准,此函数需要延迟调用
        setTimeout(()=> {
            this.getUserInfo();
            this.getClassList();
        },300)
        document.title = "停机报工小程序";
    },
    methods: {
        //获取当前用户信息
        async getUserInfo () {
            reqUserInfo().then(res => {
                if(res.data.code === 200){
                    this.userInfo.username = res.data.data.nickname;
                    this.userInfo.userId = res.data.data.id;
                    this.userInfo.userPhone = res.data.data.mobile;
                    this.userInfo.user = res.data.data.username;
                }
                console.log("获取当前用户信息",res);
            }).catch(err => {
                this.$message({type:"error",message:"网络异常，用户信息获取失败"});
            })
        },
        async getDeviceList () {
            const workshop = this.formData.workshop;
            if(workshop !== 1 && workshop !== 2){
                return;
            }
            let grid = workshop === 1 ? 143533 : 143532;
            getDeviceAPI(grid).then(res => {
                if(res.data.code === 200){
                    const equipmentList = res.data.data.map(item => {
                        return {deviceId:item.deviceId, deviceCode:item.deviceCode, deviceName:item.deviceName, gid:item.gid, gname:item.gname};
                    });
                    this.deviceList = equipmentList;
                }
                console.log('获取设备列表信息',res);
            }).catch(err => {
                this.$message({type:"error",message:"设备列表信息获取失败"});
            })
        },
        async getLineList () {
            reqLineList().then(res => {
                if(res.data.code === 200){
                    let list = res.data.data.content.map(item => item.alias);
                    let arr = list.filter(item => {
                        return (item !== null && item !== "");
                    })
                    const tmp = Array.from(new Set(arr));
                    const regex = /装配[1234567一二三四五六七]线/;
                    const lineList = tmp.filter(k => {
                        if(regex.test(k) && !k.includes("目视")){
                            return true;
                        }
                    });
                    this.lineList = lineList;
                }
                console.log('获取线体信息',res);
            }).catch(err => {
                this.$message({type:"error",message:"线体列表信息获取失败"});
            })
        },
        getClassList() {
            reqClassesList().then(res => {
                if(res.data.code === 200){
                    this.classesList = res.data.data;
                }
                console.log('获取班次信息',res);
            }).catch(err => {
                this.$message({type:"error",message:"网络异常，班次信息获取失败"});
            })
        },
        validateInput(row,index) {
            let value = row.downtTime;
            const regex = /^\d+(\.\d{0,1})?$/;
            if (!regex.test(value) && value !== '') {
                row.downtTime = value.slice(0, -1);
            }
        },
        cancelButton(){
            this.formData.reportDate = this.formatDate(null,1);
            this.formData.classList = [];
            this.formData.equipmentOrLineList = [];
            this.formData.downtReason = "";
            this.$refs.formData.resetFields();
        },
        confirmButton(){
            let checkResult = false;
            this.$refs.formData.validate((result,reason) => {
                console.log(result,reason);
                checkResult = result;
            })
            if(!checkResult){
                return;
            }
            const { workshop,reportDate,classList,equipmentList,lineList,equipmentOrLineList,downtReason } = this.formData;
            const { username,userId,userPhone,user,classTeamList } = this.userInfo;
            const parameterList = new Array();
            let tmp = equipmentOrLineList;
            for(let i = 0; i < tmp.length; i ++){
                for(let j = 0; j < classList.length; j ++){
                    const parameterItem = {
                        workReportType:"",  //线体名称:装配1/2/3..线
                        reportDate:reportDate,
                        operatorId:userId,
                        operator:user,
                        operatorPhone:userPhone,
                        username:username,
                        classes:classList[j],
                        machineCode:"",
                        workShop:workshop === 0 ? '装配线' : (workshop === 1 ? '机加工' : '走心机'),
                        workShopCode:workshop,
                        downtimeReportlList:[{downtimeType:downtReason,downtimeDuration:12}]
                    }
                    if(workshop === 0){
                        parameterItem.workReportType = tmp[i];
                    } else {
                        parameterItem.machineCode = tmp[i];
                    }
                    parameterList.push(parameterItem);
                }
            }
            reqMachieHaltReport(parameterList).then(response => {
                if(response.data.code === 200){
                    this.$message({type:"success",message:"报工成功"});
                    this.cancelButton();
                }
                console.log('批量报工api',response);
            }).catch(error => {
                this.$message({type:"error",message:"报工失败，请重试"});
                console.log('批量报工api',error);
            })
        },
        //格式化时间
        formatDate(val,type){
            let date = val === null ? new Date() : new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type === 0){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 1){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day);
            } else if (type === 2){
                return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 3){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
            }
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        }
    },
}
</script>
  
<style lang="scss" scoped>
  .content{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    user-select: none;
    .page-head{
        flex:0.5;
        padding: 1% 5%;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #4095e5;
        color: white;
        font-size: 14px;
        min-height: 50px;
    }
    @media screen and (min-width:300px) and (max-width:600px) {
        .page-head{
            width: 100%;
            height: 80px;
            align-items: flex-end;
            padding: 1% 5%;
            min-height: 100px;
        }
    }
    .page-main{
        flex: 10;
        padding: 1% 5%;
        .main-head{
            margin:20px 0;
        }
        .main-center{
            width: 100%;
            .el-form-item-content{
                width: 100%;
                max-height: 250px;
                overflow: auto;
            }
        }
        .main-footer{
            width:100%;
            margin:30px 0;
            display: flex;
            justify-content: space-evenly;
        }
    }
  }
  //表单项
  ::v-deep .form-item{
    width: 95%;
    .el-form-item__content{
        display: flex;
        align-items: center;
    }
  }
  .el-date-picker{
    width: 70%;
  }
</style>
<style lang="scss">
@media screen and (min-width:300px) and (max-width:600px) {
    .el-message-box{
        width:320px;
    }
}
</style>